package org.wisigoth.chat.client.jabber;

import java.util.LinkedList;

import org.wisigoth.chat.client.Message;
import org.wisigoth.chat.client.MessageConsumer;
import org.wisigoth.chat.client.MessageProducer;

public class MessageDispatcher implements PacketHandler, MessageProducer {

	private final LinkedList<MessageConsumer> consumers;
	private MessageConsumer unconsumedMessageConsumer;



	public MessageDispatcher() {
		this.consumers = new LinkedList<MessageConsumer>();
	}

	@Override
	public void handle(Packet packet) {
		Message message = MessageFactory.createMessage(packet);
		boolean handled = false;
		for (MessageConsumer consumer : this.consumers) {
			if (consumer.getFilter().accept(message)) {
				consumer.consume(message);
				handled = true;
			}
		}
		if (!handled && this.unconsumedMessageConsumer != null) {
			this.unconsumedMessageConsumer.consume(message);
		}
	}

	@Override
	public void addMessageConsumer(MessageConsumer consumer) {
		this.consumers.add(consumer);
	}

	@Override
	public void removeMessageConsumer(MessageConsumer consumer) {
		this.consumers.remove(consumer);
	}

	public void setUnconsumedMessageConsumer(MessageConsumer consumer) {
		this.unconsumedMessageConsumer = consumer;
	}

}
